package yxy.game.pm2.command.friend;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FriendMessage;
import yxy.game.pm2.module.friend.FriendModule;
import yxy.game.pm2.module.friend.NeedFriendList;

import java.util.Set;

/** 好友 一键接受 */
@MessageType(proto = Command.FriendReceiveOneButton, classtype = FriendMessage.FriendReceiveOneButtonRequest.class)
public class CMD_FriendReceiveOneButton extends Command<FriendMessage.FriendReceiveOneButtonRequest> {

	@Override
	public void execute(MessageSource messageSource, FriendMessage.FriendReceiveOneButtonRequest request) {
		String playerCode = messageSource.getTag();

		FriendMessage.FriendReceiveOneButtonResponse.Builder response = FriendMessage.FriendReceiveOneButtonResponse.newBuilder();

		FriendModule playerModule = FriendModule.get(playerCode);
		if (playerModule.vacant() <= 0) {
			// 玩家满了就不再添加
			send(messageSource, response, Result.FriendIsFullYou);// 你的好友名额已经满了
			return;
		}
		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());

		NeedFriendList needFriendList = new NeedFriendList(areaBean.getGroupId());
		try {
			if (playerModule.tryLock()) {
				Set<String> all = playerModule.getApply();
				for (String applyCode : all) {
					if (playerModule.vacant() <= 0) {
						break;
					}
					FriendModule applyModule = FriendModule.get(applyCode);
					try {
						if (applyModule.tryLock()) {
							if (applyModule.vacant() <= 0 || playerModule.getBlack().contains(applyCode) || applyModule.getBlack().contains(playerCode)) {
								continue;
							}
							playerModule.getFriend().add(applyCode);// 互加好友
							applyModule.getFriend().add(playerCode);
							applyModule.set();

							needFriendList.update(applyModule);

						}
					} finally {
						applyModule.unlock();
					}
				}
				playerModule.getApply().clear();// 删掉申请
				playerModule.set();
				needFriendList.update(playerModule);

				send(messageSource, response, Result.Success);
			}
		} catch (Exception e) {
			e.printStackTrace();
			send(messageSource, response, Result.DataError);
		} finally {
			playerModule.unlock();
		}

	}

	private void send(MessageSource messageSource, FriendMessage.FriendReceiveOneButtonResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}